package com.xy.wsl.api.utils;

import com.alibaba.fastjson.JSONObject;
import com.xy.wsl.api.sql.services.ThirdApp.ThirdAppService;
import io.micrometer.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
@Slf4j
public class ThirdApp {



    public static com.xy.wsl.api.sql.entity.ThirdApp.ThirdApp getAppAndToken(String appid, ThirdAppService appService) {

        com.xy.wsl.api.sql.entity.ThirdApp.ThirdApp app = appService.getWithKey(appid);
        if (app == null || StringUtils.isEmpty(app.getAppid())) {
            throw new RuntimeException("未找到对应的信息");
        }

        long currentTimeMillis = System.currentTimeMillis();
        long currentTimeInSeconds = currentTimeMillis / 1000;
//        log.info("app:" + JsonUtil.obj2json(app));

        if (StringUtils.isEmpty(app.getToken()) || app.getTokenTime() == 0
        || (currentTimeInSeconds - app.getTokenTime()) > app.getExpiresIn()) {
            //获取token
            //1716300452
            //1716300507


            if (app.getType().equals("douyin")) {
                JSONObject body = JsonUtil.create("appid",app.getAppid(),"grant_type","client_credential","secret",app.getAppsecret());
                JSONObject jsonObject = HttpUtil.doPostEvent(JsonUtil.obj2json(body),"https://developer.toutiao.com/api/apps/v2/token");
                int code = jsonObject.getInteger("err_no");
                if (code == 0) {
                    JSONObject response = jsonObject.getJSONObject("data");
                    String token = response.getString("access_token");
                    int expires_in = response.getInteger("expires_in") - 200;

                    app.setToken(token);
                    app.setExpiresIn(expires_in);
                    app.setTokenTime(currentTimeInSeconds);
                    appService.updateToken(app.getSerid(),token,expires_in,currentTimeInSeconds);
                }
            }
        }

        return  app;
    }
}
